package hui.zhang.service.take_delivery.impl;

import java.util.Date;
import java.util.Iterator;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import hui.zhang.commons.CommonUtils;
import hui.zhang.constant.Constants;
import hui.zhang.dao.base.AreaRepository;
import hui.zhang.dao.base.FixedAreaRepository;
import hui.zhang.dao.take_delivery.OrderRepository;
import hui.zhang.dao.take_delivery.WorkBillRepository;
import hui.zhang.domain.base.Area;
import hui.zhang.domain.base.Courier;
import hui.zhang.domain.base.FixedArea;
import hui.zhang.domain.base.SubArea;
import hui.zhang.domain.take_delivery.Order;
import hui.zhang.domain.take_delivery.WorkBill;
import hui.zhang.service.take_delivery.OrderService;
import oracle.net.aso.i;

/**
 * Order接口实现
 * 
 * @author hui.zhang
 * @date 2017年12月24日 下午8:40:23
 */
@Service
@Transactional
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderRepository orderRepository;

	@Autowired
	private FixedAreaRepository fixedAreaRepository;

	@Autowired
	private AreaRepository areaRepository;

	@Autowired
	private WorkBillRepository workBillRepository;

	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;

	@Override
	public void save(Order order) {
		order.setOrderNum(CommonUtils.uuid());
		order.setOrderTime(new Date());
		order.setStatus("1"); // 代取件

		// 寄件人 省市区
		Area area = order.getSendArea();
		Area persistArea = areaRepository.findByProvinceAndCityAndDistrict(area.getProvince(), area.getCity(),
				area.getDistrict());
//		System.out.println(persistArea);
		
		// 收件人 省市区
		Area recArea = order.getRecArea();
		Area persistRecArea = areaRepository.findByProvinceAndCityAndDistrict(recArea.getProvince(), recArea.getCity(),
				recArea.getDistrict());

		order.setSendArea(persistArea);
		order.setRecArea(persistRecArea);

		// 自动分单逻辑，基于crm完全匹配 获取定区 匹配快递员
		String fixedAreaId = WebClient.create(
				Constants.CRM_MANAGEMENT_URL + "/crm_management/services/customerService/customer/findFixedAreaIdByAddress"
						+ "?address=" + order.getSendAddress())
				.accept(MediaType.APPLICATION_JSON).get(String.class);
		if (fixedAreaId != null) {
			FixedArea fixedArea = fixedAreaRepository.findOne(fixedAreaId);
			Iterator<Courier> iterator = fixedArea.getCouriers().iterator();
			if(iterator.hasNext()) {
				Courier courier = iterator.next();
				if (courier != null) {
					// 自动分单成功
					System.out.println("自动分单成功！");
					saveOrder(order, courier);

					// 生成工单 发送短信
					generateWorkBill(order);
					return;
				}
			}
			
		}
		// 通过省市区 查询分区关键字 基于分区自动分单
		for (SubArea subArea : persistArea.getSubareas()) {
			// 当前客户下单地址是否包含分区关键字
			if (order.getSendAddress().contains(subArea.getKeyWords())) {
				Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
				if (iterator.hasNext()) {
					Courier courier = iterator.next();
					if (courier != null) {
						// 自动分单成功
						System.out.println("自动分单成功，关键字！");
						saveOrder(order, courier);

						// 生成工单 发送短息
						generateWorkBill(order);
						return;
					}
				}
			}
		}
		for (SubArea subArea : persistArea.getSubareas()) {
			// 是否包含辅助关键字
			if (order.getSendAddress().contains(subArea.getAssistKeyWords())) {
				Iterator<Courier> iterator = 
						subArea.getFixedArea().getCouriers().iterator();
				if(iterator.hasNext()) {
					Courier courier = iterator.next();
					if (courier != null) {
						//成功
						System.out.println("自动分单成功，辅助！");
						saveOrder(order, courier);
						//生工单
						generateWorkBill(order);
						return;
					}
				}
			}
		}
		
		//都没有成功，人工分单
		order.setOrderType("2"); //2代表人工分的
		orderRepository.save(order);

	}

	// 生成工单
	private void generateWorkBill(final Order order) {
		WorkBill workBill = new WorkBill();
		workBill.setType("新");
		workBill.setPickstate("新单"); // 取件状态
		workBill.setBuildtime(new Date());
		workBill.setRemark(order.getRemark()); // 备注
		final String smsNumber = RandomStringUtils.randomNumeric(4);
		workBill.setSmsNumber(smsNumber);
		workBill.setOrder(order);
		workBill.setCourier(order.getCourier());
		workBillRepository.save(workBill);

		// 发短信 调用MQ
		jmsTemplate.send("bos_sms", new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", order.getCourier().getTelephone());
				// 短信模板没有改，所以只能发验证码
				mapMessage.setString("msg", "短信序号：" + smsNumber + ",取件地址：" + order.getSendAddress() + ",联系人:"
						+ order.getSendName() + ",手机:" + order.getSendMobile() + "，快递员捎话：" + order.getSendMobileMsg());
				return mapMessage;
			}
		});
		System.out.println("短信序号：" + smsNumber + ",取件地址：" + order.getSendAddress() + ",联系人:" + order.getSendName()
				+ ",手机:" + order.getSendMobile() + "，快递员捎话：" + order.getSendMobileMsg());
		// 发完短信，改变状态
		workBill.setPickstate("已通知");
	}

	// 自动分单保存
	private void saveOrder(Order order, Courier courier) {
		// 将快递员关联订单
		order.setCourier(courier);
		// 设置订单类型为自动分单
		order.setOrderType("1");
		// 保存订单
		orderRepository.save(order);
	}

	
	@Override
	public Order findByOrderNum(String orderNum) {
		return orderRepository.findByOrderNum(orderNum);
	}

}
